package com.jack.netty.udp.client;

import com.jack.netty.log.DefaultLogger;
import com.jack.netty.log.LoggerManager;
import com.jack.util.hex.HexUtil;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by jack on 15/12/13.
 * UDP发送客户端
 * UDP无连接,所以不需要启动服务器,直接使用即可
 */
public class UdpClient {

    private int port = 9999; //要发动到的端口
    private String ip = "127.0.0.1"; //要发送到的地址

    public UdpClient(){

    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    /**
     * 以默认地址和端口发送字符串消息
     * @param message
     */
    public void sendMessage(String message){
        sendMessage(message,ip,port);
    }

    /**
     * 指定地址和端口发送字符串消息
     * @param message
     * @param ip
     * @param port
     */
    public void sendMessage(String message,String ip,int port){
        try {
            DatagramSocket socket = new DatagramSocket();
            byte[] bytes = message.getBytes("UTF-8");
            DatagramPacket packet = new DatagramPacket(bytes,bytes.length, InetAddress.getByName(ip),port);
            socket.send(packet);
            socket.close();
        }catch (Exception e){
            LoggerManager.getInstance().getiLogger().error(getClass(),"发送UDP消息失败:"+e.getMessage());
        }
    }

    /**
     * 指定地址和端口发送字节消息
     * @param msg
     * @param ip
     * @param port
     */
    public void sendMessage(byte[] msg,String ip,int port){
        try {
            DatagramSocket socket = new DatagramSocket();
            DatagramPacket packet = new DatagramPacket(msg,msg.length, InetAddress.getByName(ip),port);
            socket.send(packet);
            socket.close();
        }catch (Exception e){
            LoggerManager.getInstance().getiLogger().error(getClass(),"发送UDP消息失败:"+e.getMessage());
        }
    }

    public void sendMessage(byte[] msg){
        try {
            DatagramSocket socket = new DatagramSocket();
            DatagramPacket packet = new DatagramPacket(msg,msg.length, InetAddress.getByName(ip),port);
            socket.send(packet);
            socket.close();
        }catch (Exception e){
            LoggerManager.getInstance().getiLogger().error(getClass(),"发送UDP消息失败:"+e.getMessage());
        }
    }

    public static void main(String[] args){

        //设置日志
        LoggerManager.getInstance().setiLogger(new DefaultLogger());

        //初始化发送端
        UdpClient udpClient = new UdpClient();

        //设置发送地址
        udpClient.setIp("255.255.255.255");

        //设置发送端口
        udpClient.setPort(2323);

        //开始发送
        for(int i = 0 ; i < 1 ; i++){
            udpClient.sendMessage(HexUtil.HexToByteArr("51372E00000016044746313531323137554C5543553030333233475300000000000000000000000000000000AE13"));
        }
    }
}
